package com.generator.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * ZIP打包服务
 * 
 * @author Generator
 * @since 2024-01-01
 */
@Service
public class ZipService {
    
    /**
     * 将目录打包为ZIP文件
     * 
     * @param sourceDir 源目录
     * @param zipFileName ZIP文件名（不含扩展名）
     * @return ZIP文件
     */
    public File createZipFile(String sourceDir, String zipFileName) {
        try {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = zipFileName + "_" + timestamp + ".zip";
            File zipFile = new File(System.getProperty("java.io.tmpdir"), fileName);
            
            try (FileOutputStream fos = new FileOutputStream(zipFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                
                Path sourcePath = Paths.get(sourceDir);
                Files.walk(sourcePath)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        try {
                            String relativePath = sourcePath.relativize(path).toString();
                            ZipEntry zipEntry = new ZipEntry(relativePath.replace("\\", "/"));
                            zos.putNextEntry(zipEntry);
                            Files.copy(path, zos);
                            zos.closeEntry();
                        } catch (IOException e) {
                            throw new RuntimeException("添加文件到ZIP失败: " + path, e);
                        }
                    });
            }
            
            return zipFile;
            
        } catch (IOException e) {
            throw new RuntimeException("创建ZIP文件失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 清理临时ZIP文件
     * 
     * @param zipFile ZIP文件
     */
    public void cleanupZipFile(File zipFile) {
        if (zipFile != null && zipFile.exists()) {
            try {
                Files.delete(zipFile.toPath());
            } catch (IOException e) {
                // 记录日志但不抛出异常
                System.err.println("清理临时文件失败: " + zipFile.getAbsolutePath());
            }
        }
    }
}